<?php
namespace App\Templates;

use App\Models\MLog;
use App\Models\MUser;
use App\VModels\VVip;
use DB;
use Exception;
use Illuminate\Http\Request;

/**
 * 激活会员的操作处理
 */
trait ActivationUserAct
{
    public function activationUser(Request $request, $id, $in_token = null)
    {
        if (cv("switch.act_user") == 0) {
            $this->data = $this->makeJsCode(1, "该功能暂时关闭！");
            return response()->json($this->data);
        }

//        $user = MUser::find($id)->sharedLock();
        $user = MUser::where('id',$id)->sharedLock()->first();

        if (empty($user)) {
            $this->data = $this->makeJsCode(1, "要激活的用户不存在！");
            return response()->json($this->data);
        }

        if ($user->ok_status == MUser::$STATUS_ACTIVATED) {
            $this->data = $this->makeJsCode(1, "用户不可重复激活！");
            return response()->json($this->data);
        }
        $bdzx = $user->bdzxUser;

        if ($bdzx->id != ss('uid')) {
            $this->data = $this->makeJsCode(1, "您不是此用户的报单中心！");
            return response()->json($this->data);
        }

        $bdzx_wallet = $bdzx->wallet;

        $zje = VVip::attrBySlug($user->vip_slug)[MUser::$ATTR_ACTIVE];//激活会员所需总金额
        if ($request->activate_way == 1) {//报单币激活
            if ($bdzx_wallet->w2 < $zje) {
                $this->data = $this->makeJsCode(1, "报单中心报单币不足！");
                return response()->json($this->data);
            }
        } elseif ($request->activate_way == 2) {//奖金币+报单币激活
            if ($bdzx_wallet->w1 < $zje * cv("bonus.jh_jjb") || $bdzx_wallet->w2 < $zje * cv("bonus.jh_bdb")) {
                $this->data = $this->makeJsCode(1, "报单中心报单币或奖金币不足！");
                return response()->json($this->data);
            }
        }

        //检查交易密码
        $me = MUser::find(ss('uid'));
        if ($me->safepass != $request->safepass) {
            $this->data = $this->makeJsCode(1, "交易密码输入错误！");
            return response()->json($this->data);
        }

        try {
            DB::transaction(function () use (&$user, &$bdzx, &$request, $in_token) {
                if ($user->activation($bdzx, $request->activate_way)) {

                    $this->data = $this->makeJsCode(0, "激活成功！");
//                    if ($in_token == env("IN_USER_TOKEN")) {
//                        MLog::log("后台激活了用户 $user->username ( ID: $user->id ) !");
//                    }

                } else {
                    DB::rollBack();
                    $this->data = $this->makeJsCode(1, "激活失败！");
                }
            });
        } catch (Exception $exception) {
            $this->data = $this->makeJsCode(1, "激活失败！");
        }

        return response()->json($this->data);
    }
}